package com.fingard.dsp.bank.directbank.spdb01;

import java.io.File;
import java.util.*;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.spdb01.authforrec.CertificateCoder;
import com.fingard.dsp.bank.directbank.spdb01.authforrec.SocketHelper;
import com.fingard.dsp.bank.directbank.spdb01.authforrec.StringUtils;
import com.fingard.dsp.bank.directbank.spdb01.authforrec.XMLGetValueHelper;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.net.ConnState;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import com.tongtech.wtp.WtpDownloadFile;


public class SPDB01Base extends DirectBase {

    private static TransIDHelper idHelper = new TransIDHelper(1, 9999);

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    protected String getCharset(String p_for) {
        return getBankConfig().getCharset("GBK", p_for);
    }

    public byte[] sentBytesToBank(byte[] bytesToSend) throws Exception {
        String srvUrl = bankFront.getUrl("authForRec");
        WriteBankLogLnNoTime("请求服务地址：" + srvUrl);
        String[] ipAndPort = srvUrl.split(":");
        String ip = ipAndPort[0];
        int port = 0;
        if (ipAndPort.length > 1) {
            port = Integer.parseInt(ipAndPort[1]);
        }
        byte[] result = SocketHelper.sentPacket(ip, port, bytesToSend);
        return result;
    }

    public void getSessionKey(ActSetItem p_actItem) throws Exception {
        boolean needLogin = true;
        if (bankFront.customMap.containsKey("authForRec-lastLoginTime")) {
            String strLastTime = bankFront.customMap.get("authForRec-lastLoginTime");
            this.WriteBankLogLnNoTime("上次签到时间：" + strLastTime);
            Date lastLoginTime = Format.DateTimeFormat.parse(strLastTime);
            if (DateHelper.isSameDay(lastLoginTime, new Date())) {
                needLogin = false;
            }
        }

        if (needLogin) {

            String packet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
                    "<Message>\r\n" +
                    "	<Head>\r\n" +
                    "		<TransCode>04</TransCode>\r\n" +
                    "		<Version>1.0</Version>\r\n" +
                    "	</Head>\r\n" +
                    "	<Body>\r\n" +
                    "		<CorpNo>" + p_actItem.corpCode + "</CorpNo>\r\n" +
                    "	</Body>\r\n" +
                    "</Message>";

            WriteBankLogStep2("签到请求报文：" + packet);
            byte[] result = sentBytesToBank(packet.getBytes(getCharset("authForRec")));
            //byte[] result = FileHelper.readFileBytes("D:\\getToWork\\14-filesForDevelop\\SPDB01\\签到.txt");

            String xmlStr = new String(result, "GBK");
            WriteBankLogStep3("签到回复报文：" + xmlStr);
            String hexEncryptPassword = XMLGetValueHelper.getInstance(xmlStr).getString("PwdStr");
            WriteBankLogStep3("16进制密文：" + hexEncryptPassword);
            // 时间戳
            String timeStr = XMLGetValueHelper.getInstance(xmlStr).getString("TimeStr");
            bankFront.customMap.put("authForRec-timeStr", timeStr);
            this.WriteBankLogLnNoTime("authForRec-timeStr:" + timeStr);
            // 获得签到对称秘钥密文（注：请用TestCertificate.decrypt()方法进行解密）
            byte[] encryptPassword = StringUtils.hexStringToBytes(hexEncryptPassword);

            String ownKeyStorePath = p_actItem.ownKeyStorePath;
            String ownKeyPassword = p_actItem.ownKeyPassword;

            encryptPassword = CertificateCoder.decryptByPrivateKey(encryptPassword, ownKeyStorePath, "", ownKeyPassword);
            String sessionKey = new String(encryptPassword);
            bankFront.customMap.put("authForRec-sessionKey", sessionKey);
            this.WriteBankLogLnNoTime("authForRec-sessionKey:" + sessionKey);
            bankFront.customMap.put("authForRec-lastLoginTime", Format.DateTimeFormat.format(new Date()));
        }
    }

    /**
     * 获取唯一流水号
     *
     * @return
     */
    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime17SSSFormat.format(tmpDateNow);
    }

    protected String[] sendToBank(String p_reqBody, SPDB01Header p_bankHeader) throws Exception {
        String[] retStr = new String[]{"", ""};

        if (bankFront.org == null || bankFront.org.length() == 0) {
            retStr[0] = ConnState.FAIL;
            retStr[1] = "企业客户号masterID不能为空";
            return retStr;
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.transCode)) {
            retStr[0] = ConnState.FAIL;
            retStr[1] = "transCode不能为空";
            return retStr;
        }

        //WriteBankLogStep2(p_reqBody);

        String tmpAddrSign = "http://" + bankFront.serverIP + ":" + bankFront.signPort;
        WriteBankLogLn("2.提交签名的地址：" + tmpAddrSign);
        WriteBankLogLn("2.提交签名的报文：" + p_reqBody);

        WebRequest tmpWebRequestSign = new WebRequest(tmpAddrSign);
        tmpWebRequestSign.setConnectTimeout(60000);
        tmpWebRequestSign.setRequestProperty("Content-Type", "INFOSEC_SIGN/1.0");
        tmpWebRequestSign.setRequestProperty("connection", "Close");

        byte[] tmpToSignBytes = p_reqBody.getBytes(getCharset());
        String[] tmpSignStr = tmpWebRequestSign.upload(tmpToSignBytes, getCharset());

        //模拟返回
        //tmpSignStr[0]="";
        //tmpSignStr[1]=FileHelper.readFileText("D:\\Workspaces\\FilesForDevelop\\BankPort\\SPDB01\\模拟用\\1.txt", "gbk");
        //


        WriteBankLogLn("3.签名返回的结果：" + tmpSignStr[1]);
        if (tmpSignStr[0].equals(ConnState.FAIL)) {
            return tmpSignStr;
        }

        int nStartResult = tmpSignStr[1].indexOf("<html>");
        if (nStartResult < 0) {
            retStr[0] = ConnState.FAIL;
            retStr[1] = "签名失败：" + tmpSignStr[1];
            return retStr;
        }
        String signRetStr = tmpSignStr[1].substring(nStartResult);
        XmlTextReader xmlReaderSign = new XmlTextReader(signRetStr);
        String signResult = xmlReaderSign.getFirstText("/html/head/result");
        if (signResult != null && signResult.equals("0")) {
            StringBuilder sbPacket = new StringBuilder();
            sbPacket.append("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
            sbPacket.append("<packet>");
            sbPacket.append("<head>");
            sbPacket.append("<transCode>" + p_bankHeader.transCode + "</transCode>");
            sbPacket.append("<signFlag>1</signFlag>");
            Date timeNow = new Date();
            sbPacket.append("<packetID>" + Format.DateTime12Year2Format.format(timeNow) + idHelper.getNextIDStr() + "</packetID>");
            sbPacket.append("<masterID>" + bankFront.org + "</masterID>");
            sbPacket.append("<timeStamp>" + Format.DateTimeFormat.format(timeNow) + "</timeStamp>");
            sbPacket.append("</head>");

            sbPacket.append("<body>");
            sbPacket.append("<signature>");

            int idxS = signRetStr.indexOf("<sign>");
            int idxE = signRetStr.indexOf("</sign>");

            sbPacket.append(signRetStr.substring(idxS + 6, idxE));

            sbPacket.append("</signature>");
            sbPacket.append("</body>");
            sbPacket.append("</packet>");


            String strPck = sbPacket.toString();
            byte[] bytesPck = strPck.getBytes(getCharset());
            String headLen = String.format("%-6d", (bytesPck.length + 6));
            String sendPck = headLen + strPck;

            String tmpAddr = "http://" + bankFront.serverIP + ":" + bankFront.serverPort;
            WriteBankLogLn("2.提交请求的地址：" + tmpAddr);
            WriteBankLogStep2(sendPck);

            byte[] tmpToWriteBytes = sendPck.getBytes(getCharset());
            WebRequest tmpWebRequest = new WebRequest(tmpAddr);
            tmpWebRequest.setConnectTimeout(120000);
            tmpWebRequest.setRequestProperty("Content-Type", "text/plain");
            tmpWebRequest.setRequestProperty("connection", "Close");
            retStr = tmpWebRequest.upload(tmpToWriteBytes, getCharset());

            //模拟返回
            //retStr[0]="";
            //retStr[1]=FileHelper.readFileText("D:\\Workspaces\\FilesForDevelop\\BankPort\\SPDB01\\模拟用\\2.txt", "gbk");
            //

            WriteBankLogStep3(retStr[1]);
            if (retStr[0].length() == 0) {
                int indexContent = retStr[1].indexOf("<");
                if (indexContent >= 0) {
                    retStr[1] = retStr[1].substring(indexContent);
                    XmlTextReader retBkReader = new XmlTextReader(retStr[1]);
                    String retBkSignature = retBkReader.getFirstText("/packet/body/signature");
                    if (StringHelper.hasAnyChar(retBkSignature)) {
                        //验签这里不能赋值retStr[0]，因为已从银行返回内容
                        WriteBankLogLn("2.提交验签的地址：" + tmpAddrSign);
                        WebRequest tmpWebReqVerifySign = new WebRequest(tmpAddrSign);
                        tmpWebReqVerifySign.setConnectTimeout(60000);
                        tmpWebReqVerifySign.setRequestProperty("Content-Type", "INFOSEC_VERIFY_SIGN/1.0");
                        tmpWebReqVerifySign.setRequestProperty("connection", "Close");

                        byte[] bytesVerifySign = retBkSignature.getBytes(getCharset());
                        String[] verifyStr = tmpWebReqVerifySign.upload(bytesVerifySign, getCharset());

                        //模拟返回
                        //verifyStr[0]="";
                        //verifyStr[1]=FileHelper.readFileText("D:\\Workspaces\\FilesForDevelop\\BankPort\\SPDB01\\模拟用\\3.txt", "gbk");
                        //

                        WriteBankLogLn("3.验签返回的结果：" + verifyStr[1]);
                        if (verifyStr[0].length() == 0) {
                            int indexVerify = verifyStr[1].indexOf("<html>");
                            if (indexVerify >= 0) {
                                verifyStr[1] = verifyStr[1].substring(indexVerify);
                                XmlTextReader verifyReader = new XmlTextReader(verifyStr[1]);
                                String verifyResult = verifyReader.getFirstText("/html/head/result");
                                if (verifyResult != null && verifyResult.equals("0")) {
                                    String bodyTxt = verifyReader.getOuterXml("/html/body/sic/body");
                                    int indexS = retStr[1].indexOf("<body>");
                                    int indexE = retStr[1].indexOf("</body>");
                                    StringBuilder retSbBk = new StringBuilder();
                                    retSbBk.append(retStr[1].substring(0, indexS));
                                    retSbBk.append(bodyTxt);
                                    retSbBk.append(retStr[1].substring(indexE + 7, retStr[1].length()));
                                    WriteBankLogLn("经处理后最终银行返回的报文：");
                                    WriteBankLogLnNoTime(retSbBk);
                                    retStr[1] = retSbBk.toString();
                                } else {
                                    retStr[1] = "验签失败";
                                }
                            } else {
                                retStr[1] = "验签结果为空";
                            }
                        } else {
                            retStr[1] = "验签失败：" + verifyStr[1];
                        }
                    }
                }
            } else {
                return retStr;
            }
        } else {
            retStr[0] = ConnState.FAIL;
            retStr[1] = "签名失败";
            return retStr;
        }
        return retStr;
    }

    protected String[] sendToBankOSA(String p_reqBody, SPDB01Header p_bankHeader) throws Exception {
        String oraOrg = getBankConfig().getValueAsString("org");
        String oraServerIP = getBankConfig().getValueAsString("serverIP");
        String oraSignPort = getBankConfig().getValueAsString("signPort");
        String oraServerPort = getBankConfig().getValueAsString("serverPort");

        String[] retStr = new String[]{"", ""};

        if (oraOrg == null || oraOrg.length() == 0) {
            retStr[0] = ConnState.FAIL;
            retStr[1] = "企业客户号masterID不能为空";
            return retStr;
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.transCode)) {
            retStr[0] = ConnState.FAIL;
            retStr[1] = "transCode不能为空";
            return retStr;
        }

        //WriteBankLogStep2(p_reqBody);

        String tmpAddrSign = "http://" + oraServerIP + ":" + oraSignPort;
        WriteBankLogLn("2.提交签名的地址：" + tmpAddrSign);
        WriteBankLogLn("2.提交签名的报文：" + p_reqBody);

        WebRequest tmpWebRequestSign = new WebRequest(tmpAddrSign);
        tmpWebRequestSign.setConnectTimeout(60000);
        tmpWebRequestSign.setRequestProperty("Content-Type", "INFOSEC_SIGN/1.0");
        tmpWebRequestSign.setRequestProperty("connection", "Close");

        byte[] tmpToSignBytes = p_reqBody.getBytes(getCharset());
        String[] tmpSignStr = tmpWebRequestSign.upload(tmpToSignBytes, getCharset());

        //模拟返回
        //tmpSignStr[0]="";
        //tmpSignStr[1]=FileHelper.readFileText("D:\\Workspaces\\FilesForDevelop\\BankPort\\SPDB01\\模拟用\\1.txt", "gbk");
        //


        WriteBankLogLn("3.签名返回的结果：" + tmpSignStr[1]);
        if (tmpSignStr[0].equals(ConnState.FAIL)) {
            return tmpSignStr;
        }

        int nStartResult = tmpSignStr[1].indexOf("<html>");
        if (nStartResult < 0) {
            retStr[0] = ConnState.FAIL;
            retStr[1] = "签名失败：" + tmpSignStr[1];
            return retStr;
        }
        String signRetStr = tmpSignStr[1].substring(nStartResult);
        XmlTextReader xmlReaderSign = new XmlTextReader(signRetStr);
        String signResult = xmlReaderSign.getFirstText("/html/head/result");
        if (signResult != null && signResult.equals("0")) {
            StringBuilder sbPacket = new StringBuilder();
            sbPacket.append("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
            sbPacket.append("<packet>");
            sbPacket.append("<head>");
            sbPacket.append("<transCode>" + p_bankHeader.transCode + "</transCode>");
            sbPacket.append("<signFlag>1</signFlag>");
            Date timeNow = new Date();
            sbPacket.append("<packetID>" + Format.DateTime12Year2Format.format(timeNow) + idHelper.getNextIDStr() + "</packetID>");
            sbPacket.append("<masterID>" + oraOrg + "</masterID>");
            sbPacket.append("<timeStamp>" + Format.DateTimeFormat.format(timeNow) + "</timeStamp>");
            sbPacket.append("</head>");

            sbPacket.append("<body>");
            sbPacket.append("<signature>");

            int idxS = signRetStr.indexOf("<sign>");
            int idxE = signRetStr.indexOf("</sign>");

            sbPacket.append(signRetStr.substring(idxS + 6, idxE));

            sbPacket.append("</signature>");
            sbPacket.append("</body>");
            sbPacket.append("</packet>");


            String strPck = sbPacket.toString();
            byte[] bytesPck = strPck.getBytes(getCharset());
            String headLen = String.format("%-6d", (bytesPck.length + 6));
            String sendPck = headLen + strPck;

            String tmpAddr = "http://" + oraServerIP + ":" + oraServerPort;
            WriteBankLogLn("2.提交请求的地址：" + tmpAddr);
            WriteBankLogStep2(sendPck);

            byte[] tmpToWriteBytes = sendPck.getBytes(getCharset());
            WebRequest tmpWebRequest = new WebRequest(tmpAddr);
            tmpWebRequest.setConnectTimeout(120000);
            tmpWebRequest.setRequestProperty("Content-Type", "text/plain");
            tmpWebRequest.setRequestProperty("connection", "Close");
            retStr = tmpWebRequest.upload(tmpToWriteBytes, getCharset());

            //模拟返回
            //retStr[0]="";
            //retStr[1]=FileHelper.readFileText("D:\\Workspaces\\FilesForDevelop\\BankPort\\SPDB01\\模拟用\\2.txt", "gbk");
            //

            WriteBankLogStep3(retStr[1]);
            if (retStr[0].length() == 0) {
                int indexContent = retStr[1].indexOf("<");
                if (indexContent >= 0) {
                    retStr[1] = retStr[1].substring(indexContent);
                    XmlTextReader retBkReader = new XmlTextReader(retStr[1]);
                    String retBkSignature = retBkReader.getFirstText("/packet/body/signature");
                    if (StringHelper.hasAnyChar(retBkSignature)) {
                        //验签这里不能赋值retStr[0]，因为已从银行返回内容
                        WriteBankLogLn("2.提交验签的地址：" + tmpAddrSign);
                        WebRequest tmpWebReqVerifySign = new WebRequest(tmpAddrSign);
                        tmpWebReqVerifySign.setConnectTimeout(60000);
                        tmpWebReqVerifySign.setRequestProperty("Content-Type", "INFOSEC_VERIFY_SIGN/1.0");
                        tmpWebReqVerifySign.setRequestProperty("connection", "Close");

                        byte[] bytesVerifySign = retBkSignature.getBytes(getCharset());
                        String[] verifyStr = tmpWebReqVerifySign.upload(bytesVerifySign, getCharset());

                        //模拟返回
                        //verifyStr[0]="";
                        //verifyStr[1]=FileHelper.readFileText("D:\\Workspaces\\FilesForDevelop\\BankPort\\SPDB01\\模拟用\\3.txt", "gbk");
                        //

                        WriteBankLogLn("3.验签返回的结果：" + verifyStr[1]);
                        if (verifyStr[0].length() == 0) {
                            int indexVerify = verifyStr[1].indexOf("<html>");
                            if (indexVerify >= 0) {
                                verifyStr[1] = verifyStr[1].substring(indexVerify);
                                XmlTextReader verifyReader = new XmlTextReader(verifyStr[1]);
                                String verifyResult = verifyReader.getFirstText("/html/head/result");
                                if (verifyResult != null && verifyResult.equals("0")) {
                                    String bodyTxt = verifyReader.getOuterXml("/html/body/sic/body");
                                    int indexS = retStr[1].indexOf("<body>");
                                    int indexE = retStr[1].indexOf("</body>");
                                    StringBuilder retSbBk = new StringBuilder();
                                    retSbBk.append(retStr[1].substring(0, indexS));
                                    retSbBk.append(bodyTxt);
                                    retSbBk.append(retStr[1].substring(indexE + 7, retStr[1].length()));
                                    WriteBankLogLn("经处理后最终银行返回的报文：");
                                    WriteBankLogLnNoTime(retSbBk);
                                    retStr[1] = retSbBk.toString();
                                } else {
                                    retStr[1] = "验签失败";
                                }
                            } else {
                                retStr[1] = "验签结果为空";
                            }
                        } else {
                            retStr[1] = "验签失败：" + verifyStr[1];
                        }
                    }
                }
            } else {
                return retStr;
            }
        } else {
            retStr[0] = ConnState.FAIL;
            retStr[1] = "签名失败";
            return retStr;
        }
        return retStr;
    }

    protected String costItemCodeMap(String ownAct) throws Exception {

        return getBankConfig().getMapValueByKey("actCostItemCode", ownAct);

    }

    /**
     * WTP文件下载
     *
     * @param p_fileName
     * @return
     * @throws Exception
     */
    protected String[] downFileFromBank(String p_fileName, String p_saveLocalDir)
            throws Exception {
        String[] tmpStrRet = new String[]{"", ""};

        try {
            WtpDownloadFile download = new WtpDownloadFile();
            download.setRemoteFileName(p_fileName);

            download.setOverWrite(true);
            download.setLocalFileDir(p_saveLocalDir);
            int downResult = download.downLoadFile(bankFront.keyID, p_fileName);
            if (downResult != 0) {
                tmpStrRet[0] = "-1";
                tmpStrRet[1] = download.getErrorMsg();
            } else {
                tmpStrRet[0] = "";
                tmpStrRet[1] = "download completed";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception(ex.getMessage());
        }

        return tmpStrRet;
    }

    // 上送格式为json格式
    protected String[] sendToATS(String jsonData) throws Exception {
        String[] retStr = new String[]{"", ""};
        WriteBankLogLn("2.提交ATS的地址：" + FGBiz.dspCenter.dspSet.receiptPushServerUrl);

        // 发送银行前置
        WebRequest tmpRequest = new WebRequest(FGBiz.dspCenter.dspSet.receiptPushServerUrl);
        tmpRequest.setConnectTimeout(10000);
        tmpRequest.setRequestProperty("connection", "Close");
        tmpRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        String charsetName = getCharset();
        StringBuilder data = new StringBuilder();
        data.append(jsonData);
        WriteBankLogLn("3.推送给ATS的数据" + data.toString());
        byte[] tmpWriteBytes = data.toString().getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogLn("4.返回的数据" + retStr[1]);

        return retStr;
    }

    /**
     * 分割离岸户和非离岸户
     *
     * @param req7506BalQry
     * @return
     * @throws Exception
     */
    public Map<String, Req7506BalQry> getReq7506QryMap(Req7506BalQry req7506BalQry) throws Exception {
        Map<String, Req7506BalQry> map = new HashMap<String, Req7506BalQry>();
        if (req7506BalQry.isBatch) {
            XmlTextWriter xmlReq = new XmlTextWriter();//非离请求报文
            XmlTextWriter xmlReq2 = new XmlTextWriter();//离岸请求报文

            xmlReq.writeStartElement("ATSYH");
            xmlReq.writeStartElement("TransReq");
            xmlReq2.writeStartElement("ATSYH");
            xmlReq2.writeStartElement("TransReq");

            String req = req7506BalQry.getOriReqXml();
            String req7506Bal = req.substring(req.indexOf("<TransReq>") + "<TransReq>".length(), req.indexOf("<TransParam>"));

            xmlReq.directWrite(req7506Bal);
            xmlReq2.directWrite(req7506Bal);

            xmlReq.writeStartElement("TransParam");
            xmlReq2.writeStartElement("TransParam");

            XmlTextReader tmpBkReader = loadBankRespXmlReader(req7506BalQry.getOriReqXml(), new StringBuilder());
            while (tmpBkReader.read(req7506BalQry.PATH_Detail)) {
                int start = req.indexOf("<DetailRecord>");
                int end = req.indexOf("</DetailRecord>") + "</DetailRecord>".length();
                String detailRecord = req.substring(start, end);

                String balance = tmpBkReader.readedXElement.getSingleTextNotNull("ActNum");
                //离岸账户规则：OSA+14位数字
                if (StringHelper.hasAnyChar(balance) && balance.substring(0, 3).equals("OSA")) {
                    xmlReq2.directWrite(detailRecord);
                } else {
                    xmlReq.directWrite(detailRecord);
                }

                req = req.replace(detailRecord, "");
            }

            xmlReq.writeEndDocument();
            xmlReq2.writeEndDocument();

            Req7506BalQry req7506BalQry2 = new Req7506BalQry(new XmlTextReader(xmlReq.toXmlString()), req7506BalQry.reqHeader);
            Req7506BalQry req7506BalQry3 = new Req7506BalQry(new XmlTextReader(xmlReq2.toXmlString()), req7506BalQry.reqHeader);

            if (req7506BalQry2.getOriReqXml().contains("DetailRecord")) {
                map.put("0", req7506BalQry2);//非离
            }
            if (req7506BalQry3.getOriReqXml().contains("DetailRecord")) {
                map.put("1", req7506BalQry3);//离岸
            }
        } else {
            XmlTextReader tmpBkReader = loadBankRespXmlReader(req7506BalQry.getOriReqXml(), new StringBuilder());
            while (tmpBkReader.read("/ATSYH/TransReq/TransParam")) {
                String balance = tmpBkReader.readedXElement.getSingleTextNotNull("ActNum");
                //离岸账户规则：OSA+14位数字
                if (StringHelper.hasAnyChar(balance) && balance.substring(0, 3).equals("OSA")) {
                    map.put("1", req7506BalQry);//离岸
                } else {
                    map.put("0", req7506BalQry);//非离
                }
            }
        }
        return map;
    }

    /**
     * 将日期变成当月的最后一天
     */
    protected Date formatEndOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        return calendar.getTime();
    }

    /**
     * 将日期变成当月的第一天
     */
    protected Date formatFirstOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }


    public static String getRandString(int length) {
        String charList = "0123456789";
        String rev = "";
        Random f = new Random();
        for (int i = 0; i < length; i++) {
            rev += charList.charAt(Math.abs(f.nextInt()) % charList.length());
        }
        return rev;
    }

    //回单获取交易金额
    public static String getAmountStr( String[] pdfStrArr){
        String amountStr = "";
        for(String str: pdfStrArr){
            if(str.contains("人民币")){
                amountStr = str.split(" ")[1];
                break;
            }
        }
        return amountStr;
    }

    //body里的客户号根据账号匹配，如果没有匹配值则取bankfront.org值
    public String getTransMasterID(String actnum) throws Exception{
        String transMasterID = getBankConfig().getMapValueByKey("transMasterIDMapping",actnum);
        if(StringHelper.isNullOrEmpty(transMasterID)){
            WriteBankLogLn("根据"+actnum+"，在transMasterIDMapping标签中未匹配到交易客户号，发送交易客户号使用bankFront.org");
            transMasterID=bankFront.org;
        }
        return transMasterID;
    }
}
